import React,{Component} from 'react';
import { 
    View,
    FlatList, 
    StyleSheet,
    ScrollView, 
    Image, 
    Text,
    TextInput,
    TouchableWithoutFeedback, 
    StatusBar,
    Animated,
    Easing,
} from 'react-native';
import request from '../request/request';
import Header from './header/Header';
import ScrollableTabView, {DefaultTabBar} from 'react-native-scrollable-tab-view';
export default class AddNewAddress extends Component {

    constructor(props) {
        super(props);
        this.state = {
            // 是否设为默认地址
            isDefault: false,
            // 控制tab所在的页数
            page: 0,
            // 暂时存放用户所选择的区域
            addressTep: ['','',''],
            // 显示用户所选择的区域
            addressInfo: '请选择',
            // 收货信息
            id: '',
            name: '',
            mobile: '',
            addressId: '',
            address: '',
            // 弹窗初始数据
            currentPosition: 350,//缩放标志位，记录当前value
            position: new Animated.Value(350), //设置初始值
            // 弹窗的显示与隐藏
            mask: false,
            // 省市区数据
            provinceData: [],
            cityData: [],
            areaData: [],
        };
    }

    componentDidMount(){
    	const { params } = this.props.navigation.state;
        let that = this;
        that.setState({
        	isDefault: params.isDefault,
            id: params.id,
            name: params.name,
            mobile: params.mobile,
            addressId: params.addressId,
            addressInfo: params.addressInfo,
            address: params.address,
        });
        fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id=100000',
            {
                method: 'GET',
            }
        )
        .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
        .then((responseData) => {   // 获取到的数据处理
            for(let i=0;i<responseData.result.length;i++){
                responseData.result[i].isChoose = false;
            }
            that.setState({
                provinceData: responseData.result
            });
            console.log(responseData.result)
        })
        .catch((error) => {     // 错误处理
            console.log(666)
        })
        .done();
    }

    getCityData(data, index){
        let that = this;
        this.state.addressTep[0] = '';
        for(let i=0;i<this.state.provinceData.length;i++){
            if(i==index){
                this.state.provinceData[i].isChoose = true;
                
                this.state.addressTep[0] = this.state.provinceData[i].name;
            }else {
                this.state.provinceData[i].isChoose = false;
            }
        }
        this.setState({
            page: 1,
            addressTep: this.state.addressTep,
            provinceData: this.state.provinceData,
            cityData: [],
            areaData: [],
        },function(){
            fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id='+data,
                {
                    method: 'GET',
                }
            )
            .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
            .then((responseData) => {   // 获取到的数据处理
                for(let i=0;i<responseData.result.length;i++){
                    responseData.result[i].isChoose = false;
                }
                that.setState({
                    cityData: responseData.result
                });
                console.log(responseData.result)
            })
            .catch((error) => {     // 错误处理
                console.log(666)
            })
            .done();
        });
    }

    getAreaData(data, index){
        let that = this;
        this.state.addressTep[1] = '';
        for(let i=0;i<this.state.cityData.length;i++){
            if(i==index){
                this.state.cityData[i].isChoose = true;
                this.state.addressTep[1] = this.state.cityData[i].name;
            }else {
                this.state.cityData[i].isChoose = false;
            }
        }
        this.setState({
            page: 2,
            addressTep: this.state.addressTep,
            cityData: this.state.cityData,
            areaData: [],
        },function(){
            fetch('http://www.hahafit.com/api.php?method=haha.haha.getChildren&id='+data,
                {
                    method: 'GET',
                }
            )
            .then((response) => response.json())  // json方式解析，如果是text就是 response.text()
            .then((responseData) => {   // 获取到的数据处理
                for(let i=0;i<responseData.result.length;i++){
                    responseData.result[i].isChoose = false;
                }
                that.setState({
                    areaData: responseData.result
                });
                // console.log(responseData)
            })
            .catch((error) => {     // 错误处理
                console.log(666)
            })
            .done();
        });
    }

    chooseFinish(data, index){
        let that = this;
        this.state.addressTep[2] = '';
        for(let i=0;i<this.state.areaData.length;i++){
            if(i==index){
                this.state.areaData[i].isChoose = true;
                this.state.addressTep[2] = this.state.areaData[i].name;
            }else {
                this.state.areaData[i].isChoose = false;
            }
        }
        this.state.addressInfo = this.state.addressTep.join(' ');
        this.chooseAddress();
        this.setState({
            addressId: data,
            addressTep: this.state.addressTep,
            addressInfo: this.state.addressInfo,
        })
    }

    saveAddress(){
        alert(this.state.name)
    }

    setDefaulst(){
        this.setState({
            isDefault: !this.state.isDefault
        });
    }

    chooseAddress(){
        let that = this;
        this.setState({
            mask: !this.state.mask
        },function () {
            that.state.currentPosition = that.state.currentPosition==350?0:350;
            Animated.spring(
                that.state.position,
                {
                    toValue: that.state.currentPosition,
                    easing: Easing.linear,
                    speed: 8,
                    bounciness: 5,
                    useNativeDriver: true
                }
            ).start()
        });
        
    }

    render() {
        const { params } = this.props.navigation.state;
        const {navigate,goBack,state} = this.props.navigation;
        let barHeight = StatusBar.currentHeight;
        return (
            <View style={{
                flex: 1,
                // paddingTop: barHeight, 
                backgroundColor: '#eaeaea'
            }}>
                <Header isShowBack={true} title='编辑地址' goBack={goBack} />
                <View style={{height: 40, paddingLeft: 12, paddingRight: 12, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#f4f4f4', backgroundColor: '#fff'}}>
                    <Text style={{fontSize: 13, color: '#626262'}}>收货人</Text>
                    <TextInput
                        style={{
                            width: 200,
                            height: 19,
                            padding: 0,
                            paddingLeft: 8,
                            fontSize: 13,
                            textAlign: 'right',
                            color: '#626262'
                        }}
	                    defaultValue={this.state.name}
                        placeholder={'请填写收货人'}
                        placeholderTextColor='#747474'
                        underlineColorAndroid={'transparent'}
                        onChangeText={(text)=>this.setState({name: text})}
                    />
                </View>
                <View style={{height: 40, paddingLeft: 12, paddingRight: 12, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#f4f4f4', backgroundColor: '#fff'}}>
                    <Text style={{fontSize: 13, color: '#626262'}}>手机号码</Text>
                    <TextInput
                        style={{
                            width: 200,
                            height: 19,
                            padding: 0,
                            paddingLeft: 8,
                            fontSize: 13,
                            textAlign: 'right',
                            color: '#626262'
                        }}
                        defaultValue={this.state.mobile}
                        placeholder={'请填写手机号'}
                        placeholderTextColor='#747474'
                        underlineColorAndroid={'transparent'}
                        onChangeText={(text)=>this.setState({mobile: text})}
                    />
                </View>
                <TouchableWithoutFeedback onPress={()=>this.chooseAddress()}>
                    <View style={{height: 40, paddingLeft: 12, paddingRight: 12, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#f4f4f4', backgroundColor: '#fff'}}>
                        <Text style={{fontSize: 13, color: '#626262'}}>所在区域</Text>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            <Text style={{fontSize: 13, color: '#626262'}}>{this.state.addressInfo}</Text>
                            <Image style={{
                                width: 8,
                                height: 16,
                                marginLeft: 8,
                            }} source={require('../images/rightGo.png')}/>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
                <View style={{height: 40, paddingLeft: 12, paddingRight: 12, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#f4f4f4', backgroundColor: '#fff'}}>
                    <Text style={{fontSize: 13, color: '#626262'}}>详细地址</Text>
                    <TextInput
                        style={{
                            width: 200,
                            height: 19,
                            padding: 0,
                            paddingLeft: 8,
                            fontSize: 13,
                            textAlign: 'right',
                            color: '#626262'
                        }}
                        defaultValue={this.state.address}
                        placeholder={'请填写详细地址'}
                        placeholderTextColor='#747474'
                        underlineColorAndroid={'transparent'}
                        onChangeText={(text)=>this.setState({address: text})}
                    />
                </View>
                <View style={{padding: 12, marginBottom: 45}}>
                    <TouchableWithoutFeedback onPress={()=>this.setDefaulst()}>
                        <View style={{flexDirection: 'row', alignItems: 'center'}}>
                            {
                                this.state.isDefault?
                                <Image style={{
                                    width: 18,
                                    height: 18,
                                    marginRight: 3,
                                }} source={require('../images/address-active.png')}/>
                                :
                                <Image style={{
                                    width: 18,
                                    height: 18,
                                    marginRight: 3,
                                }} source={require('../images/address.png')}/>
                            }
                            <Text style={{fontSize: 13, lineHeight: 18}}>设为默认地址</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
                
                <View style={{height: 50, alignItems: 'center'}}>
                    <TouchableWithoutFeedback onPress={() =>this.saveAddress()}>
                        <View style={{
                            width: 235,height: 42,borderRadius: 5,backgroundColor: '#fff',justifyContent: 'center', alignItems: 'center',

                        }}>
                            <Text style={{fontSize: 16, color: '#0000ff', textAlign: 'center'}}>保存地址</Text>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
                

                {/* 省市联动弹窗 */}
                {
                    this.state.mask?
                    <TouchableWithoutFeedback onPress={()=>this.chooseAddress()}>
                        <View style={{position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, backgroundColor: 'rgba(0,0,0,0.4)', zIndex: 100}}></View>
                    </TouchableWithoutFeedback>
                    :
                    null
                }
                
                <Animated.View style={{height: '50%', position: 'absolute', left: 0, right: 0, bottom: 0, transform: [{translateY:this.state.position}], backgroundColor: '#fff', zIndex: 1000}}>
                    <View style={{height: 36, justifyContent: 'center', alignItems: 'center'}}>
                        <Text>配送至</Text>
                    </View>
                    <ScrollableTabView
                        // 默认选项卡栏下划线的样式
                        tabBarUnderlineStyle={{height: 2, backgroundColor: '#0000ff'}}
                        // 默认标签栏背景的颜色，默认为white
                        tabBarBackgroundColor={'white'}
                        // 选中时默认标签栏文本的颜色，默认为navy
                        tabBarActiveTextColor={'#0000ff'}
                        // 不选中时默认标签栏文本的颜色，默认为black
                        tabBarInactiveTextColor={'black'}
                        // 标签栏文本的其他样式
                        tabBarTextStyle={{fontSize: 14, fontWeight: 'normal'}}
                        // 最初选择的选项卡的索引，默认为0 ===第一个选项卡
                        initialPage={0}
                        // 动态设置当前显示的tab
                        page={this.state.page}
                        // TabBar组件
                        renderTabBar={() => <DefaultTabBar style={{height: 30}} />}
                        // 当选项卡更改时调用的函数。i：页面下标，ref：所选标签的引用
                        // onChangeTab={(obj)=>console.log(obj.i,obj.ref)}
                        // onChangeTab={this._tabChoose.bind(this)}
                        // 页面滑动时调用的函数。num：选项卡所处的位置
                        // onScroll={(num)=>console.log(num)}
                    >
                        <ScrollView
                            tabLabel='省级'
                        >
                            {
                                this.state.provinceData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.getCityData(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                        <ScrollView
                            tabLabel='市级'
                        >
                            {
                                this.state.cityData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.getAreaData(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                        <ScrollView
                            tabLabel='地区'
                        >
                            {
                                this.state.areaData.map((item, index)=>
                                    <TouchableWithoutFeedback key={item.id} onPress={()=>this.chooseFinish(item.id, index)}>
                                        <View style={styles.cityBox}>
                                            <Text style={styles.cityBoxText}>{item.name}</Text>
                                            {
                                                item.isChoose?
                                                <Image style={{
                                                    width: 18,
                                                    height: 18,
                                                    marginRight: 3,
                                                }} source={require('../images/address-active.png')}/>
                                                :
                                                null
                                            }
                                        </View>
                                    </TouchableWithoutFeedback>
                                )
                            }
                        </ScrollView>
                    </ScrollableTabView>
                </Animated.View>
            </View>
        )
    }
}
const styles = StyleSheet.create({
    cityBox: {paddingLeft: 10, paddingRight: 10, height: 34, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: 1, borderColor: '#ddd'},
    cityBoxText: {fontSize: 13, color: '#000'},
});